package com.sizengli.learn;

import javassist.*;

import java.io.IOException;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;


public class MyTransformer implements ClassFileTransformer {
    @Override
    public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
        if(className.equals("com/atguigu/boot/controller/HelloController")){
            System.out.println("========================MyTransformer======================");
            try {
                CtClass ctClass = ClassPool.getDefault().get(className.replaceAll("/", "."));
                if(ctClass.isFrozen()){
                    ctClass.defrost();
                }
                CtMethod hello = ctClass.getDeclaredMethod("hello");
                hello.insertBefore("System.out.println(\"hello() 方法开始执行\");");
                hello.insertAfter("System.out.println(\"hello() 执行完毕\");");
                return ctClass.toBytecode();
            } catch (NotFoundException | CannotCompileException | IOException e) {
                System.out.println(e.getMessage());
                e.printStackTrace();
            }

        }
        return classfileBuffer;
    }
}
